import os
import datetime


def get_current_date_folder():
    """获取当前日期对应的文件夹路径"""
    now = datetime.datetime.now()
    year_folder = str(now.year)
    month_folder = str(now.month).zfill(2)
    folder_path = os.path.join(year_folder, month_folder)
    # 检查文件夹是否存在，不存在则创建
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    return folder_path


def save_to_file(serial_number, barcode, result):
    """将记录保存到文件中"""
    date_folder = get_current_date_folder()
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
    # 构建文件名
    file_name = now.strftime("%y%m%d.csv")
    file_path = os.path.join(date_folder, file_name)
    # 检查文件是否存在，如果不存在则写入标题行
    is_new_file = not os.path.exists(file_path)
    with open(file_path, "a", encoding="gbk") as f:
        if is_new_file:
            f.write("序号,时间,条码,判断结果\n")
        # 写入数据
        f.write(f"{serial_number},{timestamp},{barcode},{result}\n")


def main():
    serial_number = 1
    while True:
        # 模拟扫码枪输入
        barcode = input("请扫描条码（输入 'q' 退出）: ")
        if barcode.lower() == 'q':
            break
        while True:
            try:
                # 接收判断数字
                judgment = input("请输入判断结果（1 表示 OK，0 表示 NG）: ")
                if judgment == '1':
                    result = "OK"
                    break
                elif judgment == '0':
                    result = "NG"
                    break
                else:
                    print("输入无效，请输入 1 或 0。")
            except ValueError:
                print("输入无效，请输入 1 或 0。")

        # 保存记录到文件
        save_to_file(serial_number, barcode, result)
        serial_number += 1


if __name__ == "__main__":
    main()